package org.zhangsh.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-17
 */
public class ThreadPoolServer {

    public static final ExecutorService executor = Executors.newCachedThreadPool();

    public static void main(String[] args) throws IOException {

        int port = 7777;
        ServerSocket serverSocket = new ServerSocket(port);

        System.out.println(Thread.currentThread().getName() + ": 服务端启动...");

        while (true) {
            // 阻塞点
            Socket socket = serverSocket.accept();
            executor.submit(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + ": 新客户端连接...");
                    InputStream inputStream = socket.getInputStream();

                    while(true){
                        byte[] b = new byte[1024];
                        // 阻塞点
                        int data = inputStream.read(b);
                        if (data != -1) {
                            String info = new String(b, 0, data, "GBK");
                            System.out.println(Thread.currentThread().getName() + ": " + info);
                        } else {
                            System.out.println(Thread.currentThread().getName() + "退出");
                            break;
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
